//
//  LoginViewController.m
//  HeXun
//
//  Created by ibokan on 15/11/16.
//  Copyright © 2015年 LGC. All rights reserved.
//

#import "LoginViewController.h"
#import "ZJSwitch.h"
#import "RegisterSucceedViewController.h"


@interface LoginViewController ()
{
    //登录用户名文本框
    __weak IBOutlet UITextField *_userNameTextField;
    
    //密码文本框
    __weak IBOutlet UITextField *_passWordTextField;
    
    
    
    //设置用户名的文本框
    __weak IBOutlet UITextField *_setUserNameTextField;
    
    //设置密码的文本框
    __weak IBOutlet UITextField *_setPassWordTextField;
    
    //输入验证码的文本框
    __weak IBOutlet UITextField *_verificationCodeTextField;
    
    //显示验证码的button
    __weak IBOutlet UIButton *_verificationCodeButton;
    
}
@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    //文本框内容有任何改变时，触发相应的方法
    [_setUserNameTextField addTarget:self action:@selector(myTextFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [_setPassWordTextField addTarget:self action:@selector(myTextFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [_verificationCodeTextField addTarget:self action:@selector(myTextFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    
    //键盘样式
    _setUserNameTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    
    //输入验证码的文本框的键盘只能是 数字键盘
    _verificationCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    //加载随机验证码
    [self getVerificationCode];
    
    
    //密码框上的开关键
    ZJSwitch *aSwitch = [[ZJSwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 23)];
    [_setPassWordTextField addSubview:aSwitch];
    [aSwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    //通过控制开关的中心来控制开关在密码框上的位置
    CGPoint switchCenter = aSwitch.center;
    switchCenter.x = _setPassWordTextField.frame.size.width - 25;
    switchCenter.y = _setPassWordTextField.frame.size.height / 2;
    aSwitch.center = switchCenter;
    
    //开关的相关设置
    aSwitch.onText = @"····";
    aSwitch.offText = @"abc";
    aSwitch.onTintColor = [UIColor colorWithWhite:0.75 alpha:1.0];
    aSwitch.thumbTintColor = [UIColor redColor];
    [aSwitch setOn:YES];
    
    
}

#pragma mark - 点击登录，触发的方法
- (IBAction)userLogin:(UIButton *)sender
{
    //调用登录的方法
    BOOL loginState = [self checkoutUserInformation:_userNameTextField.text forPassword:_passWordTextField.text];
    
    if (loginState)
    {
        NSLog(@"登录成功");
        //实现页面跳转
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    else
    {
        NSLog(@"登录失败");
    }
}


#pragma mark - 点击注册，触发的方法
- (IBAction)userRegister:(UIButton *)sender
{
    //调用注册的方法
    BOOL registerState = [self addUserInformation:_setUserNameTextField.text forPassword:_setPassWordTextField.text forVerificationCode:_verificationCodeTextField.text];
    
    //根据注册方法返回的值判断注册是否成功
    if (registerState)
    {
        //注册成功，跳转传值，把注册的用户名传给下一个控制器
        [self performSegueWithIdentifier:@"registerSucceed" sender:_setUserNameTextField.text];
    }
    else
    {
        NSLog(@"注册失败");
    }
}



#pragma mark - 随机产生验证码的方法
- (IBAction)getVerificationCode
{
    //产生 0～9999 之间的随机整数
    NSInteger value = arc4random() % 9000 + 1000;
    
    //把这个随机数赋值给button
    [_verificationCodeButton setTitle:[NSString stringWithFormat:@"%ld", value] forState:UIControlStateNormal];
}



#pragma mark - 普通的键盘回收
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}

#pragma mark - 点击空白处回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_setUserNameTextField resignFirstResponder];
    [_setPassWordTextField resignFirstResponder];
    [_verificationCodeTextField resignFirstResponder];
}


#pragma mark - 限制三个文本框的输入
-(void)myTextFieldDidChanged:(UITextField *)textField
{
    //
    if (_setUserNameTextField.isEditing)
    {
        //判断输入的文字是否为汉字
        for (int i = 0; i < textField.text.length; i++)
        {
            //循环提取每个字符
            unichar c = [textField.text characterAtIndex:i];
            
            //判断是否为汉字
            if (c >= 0x4e00 && c <= 0x9fff)
            {
                NSLog(@"不能输入汉字");
                
                //如果输入的是汉字，则文本框只显示汉字前面的字符
                if (i == 0)
                {
                    _setUserNameTextField.text = @"";
                }
                else
                {
                    _setUserNameTextField.text = [textField.text substringToIndex:i];
                }
                
            }
        }
        
        //限制最大长度为20
        if (textField.text.length > 20)
        {
            _setUserNameTextField.text = [textField.text substringToIndex:20];
        }
        
    }
    else if (_setPassWordTextField.isEditing)
    {
        //判断输入的文字是否为汉字
        for (int i = 0; i < textField.text.length; i++)
        {
            //循环提取每个字符
            unichar c = [textField.text characterAtIndex:i];
            
            //判断是否为汉字
            if (c >= 0x4e00 && c <= 0x9fff)
            {
                NSLog(@"不能输入汉字");
                
                //如果输入的是汉字，则文本框只显示汉字前面的字符
                if (i == 0)
                {
                    _setPassWordTextField.text = @"";
                }
                else
                {
                    _setPassWordTextField.text = [textField.text substringToIndex:i];
                }
                
            }
        }
        
        //限制最大长度为12
        if (textField.text.length > 12)
        {
            _setPassWordTextField.text = [textField.text substringToIndex:12];
        }
    }
    else if (_verificationCodeTextField.isEditing)
    {
        //限制最大长度为4
        if (textField.text.length > 4)
        {
            _verificationCodeTextField.text = [textField.text substringToIndex:4];
        }
    }
    
}
 

#pragma mark - 开关键改变触发的方法
-(void)switchValueChanged:(ZJSwitch *)aSwitch
{
    //通过开关，控制密码框的密码是否可见
    if (aSwitch.on == YES)
    {
        _setPassWordTextField.secureTextEntry = YES;     //密码不可见
    }
    
    if (aSwitch.on == NO)
    {
        _setPassWordTextField.secureTextEntry = NO;      //密码可见
    }
    
}

#pragma mark - 注册用户信息
-(BOOL)addUserInformation:(NSString *)name forPassword:(NSString *)password forVerificationCode:(NSString *)verificationCode
{
    NSMutableString *errorMessage = [NSMutableString new];
    [errorMessage setString:@" "];
    
    //首先，三个参数都有有效值
    if (![name isEqualToString:@""] && ![password isEqualToString:@""] && ![verificationCode isEqualToString:@""])
    {
        //用户名是合法的邮箱地址，且验证码正确，密码暂不做判断
        if ( [self isValidateEmail:name] && [verificationCode isEqualToString:_verificationCodeButton.titleLabel.text])
        {
            //将用户名、密码写入本地文件保存起来，以便登录时校验
            [self writeUserInformation];
            return YES;
        }
        
        
        //如果用户名或验证码有任何一个有问题，则做相应判断并给出错误提示
        //邮箱地址不合法
        if (![self isValidateEmail:name])
        {
            [errorMessage appendString:@"邮箱地址 "];
        }
        
        //验证码不正确
        if (![verificationCode isEqualToString:_verificationCodeButton.titleLabel.text])
        {
            [errorMessage appendString:@"验证码 "];
        }
        
        
        //如果邮箱地址或验证码不正确，则弹出提示框，提示相应错误
        if (![self isValidateEmail:name] || ![verificationCode isEqualToString:_verificationCodeButton.titleLabel.text])
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:[NSMutableString stringWithFormat:@"您输入的%@不正确，请重新输入！", errorMessage] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
        return NO;
    }
    
    
    
    //如果三个参数有任何一个不是有效值，则做相应判断并给出错误提示
    if ([name isEqualToString:@""])
    {
        [errorMessage appendString:@"用户名 "];
    }
    
    if([password isEqualToString:@""])
    {
        [errorMessage appendString:@"密码 "];
    }
    
    if([verificationCode isEqualToString:@""])
    {
        [errorMessage appendString:@"验证码 "];
    }
    
    //如果有任何一个为空，则弹出提示框，提示相应错误
    if ([name isEqualToString:@""] || [password isEqualToString:@""] || [verificationCode isEqualToString:@""])
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:[NSMutableString stringWithFormat:@"您输入的%@为空，请重新输入！", errorMessage] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    return NO;
}

#pragma mark - 利用正则表达式验证邮箱地址的合法性
-(BOOL)isValidateEmail:(NSString *)email
{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}


#pragma mark - 将注册的用户名、密码写入本地文件
-(void)writeUserInformation
{
    //构建文件路径
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *userNamePath = [documentsPath stringByAppendingString:@"userName.plist"];
    NSLog(@"userName: %@", userNamePath);
    
    //先从文件路径中拿到字典
    NSMutableDictionary *userNameDict = [NSMutableDictionary dictionaryWithContentsOfFile:userNamePath];
    
    //如果是第一次创建文件，则字典为空
    if (userNameDict == nil)
    {
        userNameDict = [NSMutableDictionary new];
        
        //将用户信息加入字典中
        [userNameDict setObject:[NSString stringWithFormat:@"%@", _setPassWordTextField.text] forKey:[NSString stringWithFormat:@"%@", _setUserNameTextField.text]];
    }
    else
    {
        //先判断这次写入的用户名是否已经存在
        //拿到字典中所有的用户名
        NSArray *userNameArray = userNameDict.allKeys;
        
        //是否找到重名的布尔值
        BOOL searchResult = NO;
        
        //遍历数组，看是否有重名
        for (NSInteger i = 0; i < userNameArray.count; i++)
        {
            //有重名
            if ([userNameArray[i] isEqualToString:_setUserNameTextField.text])
            {
                searchResult = YES;
                break;
            }
        }
        
        //有重名
        if (searchResult)
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:@"此用户名已被注册过" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else   //无重名
        {
            //将用户信息加入字典中
            [userNameDict setObject:[NSString stringWithFormat:@"%@", _setPassWordTextField.text] forKey:[NSString stringWithFormat:@"%@", _setUserNameTextField.text]];
        }
    }
    
    
    //将字典写入本地文件
    if (![userNameDict writeToFile:userNamePath atomically:YES])
    {
        NSLog(@"写入用户信息失败！");
    }
    
}


#pragma mark - 校验用户登录的用户名和密码
-(BOOL)checkoutUserInformation:(NSString *)name forPassword:(NSString *)password
{
    NSMutableString *errorMessage = [NSMutableString new];
    [errorMessage setString:@" "];
    
    //首先，两个参数都有有效值
    if (![name isEqualToString:@""] && ![password isEqualToString:@""])
    {
        //构建文件路径
        NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *userNamePath = [documentsPath stringByAppendingString:@"userName.plist"];
        NSLog(@"userName: %@", userNamePath);
        
        //先从文件路径中拿到字典（字典中有所有的用户名和密码）
        NSMutableDictionary *userNameDict = [NSMutableDictionary dictionaryWithContentsOfFile:userNamePath];
        
        //首先要校验此登录的用户名是否存在（是否注册过）
        //从字典中拿出所有的用户名
        NSArray *allUserNameArray = userNameDict.allKeys;
        
        //是否找到此用户名的布尔值
        BOOL searchResult = NO;
        
        //遍历数组，看是否有此登录用户名
        for (NSInteger i = 0; i < allUserNameArray.count; i++)
        {
            //找到此用户
            if ([allUserNameArray[i] isEqualToString:_userNameTextField.text])
            {
                searchResult = YES;
                break;
            }
        }
        
        
        if (searchResult)
        {
            //有此用户
            //校验用户和密码是否匹配
            //通过此用户名去字典中拿到密码
            NSString *password = [userNameDict objectForKey:_userNameTextField.text];
            
            //判断用户名和密码是否匹配
            //用户名和密码匹配成功
            if ([_passWordTextField.text isEqualToString:password])
            {
                //匹配成功，在外面实现页面跳转
                return YES;
                
            }
            else     //用户名和密码匹配不成功，弹框提示
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:@"密码错误！请重新输入。" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:okAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
            
        }
        else
        {
            //没有此用户，弹框提示
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:@"此用户名不存在，请重新输入或注册！" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }
    
    
    
    //如果两个参数有任何一个不是有效值，则做相应判断并给出错误提示
    if ([name isEqualToString:@""])
    {
        [errorMessage appendString:@"用户名 "];
    }
    
    if([password isEqualToString:@""])
    {
        [errorMessage appendString:@"密码 "];
    }
    
    //如果有任何一个为空，则弹出提示框，提示相应错误
    if ([name isEqualToString:@""] || [password isEqualToString:@""])
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误提示" message:[NSMutableString stringWithFormat:@"您输入的%@为空，请重新输入！", errorMessage] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    return NO;
}




#pragma mark - 内存占用过多警告
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    NSLog(@"内存占用过多");
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    RegisterSucceedViewController *succeedViewController = segue.destinationViewController;
    succeedViewController.myEmail = sender;
}


@end
